package com.jrx.anytxn.transaction.timer.job.queryPaymentStatus.step;

import com.alibaba.fastjson.JSONObject;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.customer.constant.CustomerConstant;
import com.jrx.anytxn.feign.common.GateWayPredicate;
import com.jrx.anytxn.feign.gateway.bean.ApiResponse;
import com.jrx.anytxn.feign.gateway.response.CoreResponse16;
import com.jrx.anytxn.feign.gateway.response.PaymentResponse04;
import com.jrx.anytxn.feign.gateway.service.IInnerGatewayService;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.TlPaymentLog;
import com.jrx.anytxn.transaction.service.IDealGatewayService;
import com.jrx.anytxn.transaction.service.ISmsService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * 还款查询 - processor
 *
 * @author jing.xy
 */
@Service
public class QueryPaymentStatusProcessor implements ItemProcessor<TlPaymentLog, TlPaymentLog> {

    Logger logger = LoggerFactory.getLogger(QueryPaymentStatusProcessor.class);

    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private IDealGatewayService dealGatewayService;
    @Lazy
    @Autowired
    private IInnerGatewayService innerGatewayService;
    @Autowired
    private ISmsService iSmsService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    @Override
    public TlPaymentLog process(TlPaymentLog log) throws Exception {
        PrOrganizationTable organization = organizationTableService.findByOrId(log.getOrganizationId(), log.getTenantId());
        Date businessDate = organization.getNextProcessingDate();//机构上 当天日期

        TlPaymentLog updateLog = new TlPaymentLog();
        updateLog.setId(log.getId());
        updateLog.setCustomerId(log.getCustomerId());
        updateLog.setTenantId(log.getTenantId());
        String result;
        String busCode;
        String busMsg;
        if (Constant.THIRD_CHANNEL.equalsIgnoreCase(log.getThirdChannel())) {
            String coreRequest16Json = dealGatewayService.buildInterestCompensateReq(log);
            CoreResponse16 res = null;
            try {
                GateWayPredicate<CoreResponse16> core16Pre = () -> innerGatewayService.interestCompensate(coreRequest16Json);
                res = core16Pre.getRes(core16Pre);
            } catch (Exception e) {
                //  查询接口与互转交易服务接口同一个 保证请求流水号和serviceCode一致即可
                logger.error("调用微信还款查询接口出现异常", e);
            }
            if (res == null || !CustomerConstant.GATEWAY_BUS_CODE_SUC.equalsIgnoreCase(res.getBusCode())) {
                updateLog.setSumStatus(TransBizConstant.PAYMENT_LOG_SUM_STATUS_O);
                updateLog.setCompleteTime(DateUtils.getBusinessTime(new Date(), businessDate));
                return null;
            }

            logger.info("用户：{}调用微信还款查询接口结果：{}", log.getCustomerId(), JSONObject.toJSONString(res));

            result = res.getDealState();
            busCode = res.getBusCode();
            busMsg = res.getBusMsg();
        } else {
            PaymentResponse04 res;
            try {
                String paymentRequest04Json = dealGatewayService.buildQueryTansStatReq(log);
                ApiResponse<PaymentResponse04> response = innerGatewayService.queryTransactionStatus(paymentRequest04Json);
                if (Objects.isNull(response) || Objects.isNull(response.getData())
                        // 内部系统交互失败
                        || TransBizConstant.GATEWAY_SUC != response.getCode()
                        // 行内网关交互失败
                        || (!CustomerConstant.GATEWAY_BUS_CODE_SUC.equalsIgnoreCase(response.getData().getBusCode())
                                && !response.getData().getBusMsg().contains(TransBizConstant.NO_RECODE)
                           )
                        || response.getData().getBusMsg().contains(TransBizConstant.GATEWAY_CONTENT_TIMEOUT)) {
                    logger.warn("调用查询接口出现异常:{}", JSONObject.toJSONString(response));
                    return null;
                }
                res = response.getData();
            } catch (Exception e) {
                logger.error("调用查询接口出现异常:{}", e);
                return null;
            }
            result = res.getOrigDealResult();
            busCode = res.getBusCode();
            busMsg = res.getBusMsg();
        }

        updateLog.setReturnCode(busCode);
        updateLog.setReturnStatus(result);
        updateLog.setCompleteTime(DateUtils.getBusinessTime(new Date(), businessDate));

        if (TransBizConstant.GATEWAY_DEAL_SUC.equals(result)) { //成功
            updateLog.setSumStatus(TransBizConstant.PAYMENT_LOG_SUM_STATUS_T);
            updateLog.setCollateDate(businessDate);
        } else if (TransBizConstant.GATEWAY_DEAL_FAIL.equals(result)) {//失败
            updateLog.setSumStatus(TransBizConstant.PAYMENT_LOG_SUM_STATUS_F);
            busMsg = "失败";
            updateLog.setCollateDate(businessDate);
        }
        //updateLog.setReturnMsg(busMsg);
        //log.setReturnMsg(busMsg);
        logger.info("queryTransactionStatus用户{}还款批次的结果为{}", log.getCustomerId(), updateLog.getSumStatus());
        //添加短信逻辑 只有拿到终态才需要处理
        if (TransBizConstant.PAYMENT_LOG_SUM_STATUS_F.equals(updateLog.getSumStatus())) {
            log.setSumStatus(TransBizConstant.PAYMENT_LOG_SUM_STATUS_F);
            try {
                iSmsService.paymentProcess(log);
            } catch (Exception e) {
                logger.error("短信发送异常", e);
            }
        }

        return updateLog;
    }

}
